package seismosurfer.http;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * A utility for url management.
 *  
 */
public class URLUtil {

    protected static URLUtil urlUtil;

    public static final String QUERY = "query";

    public static final String UPDATE = "update";

    public static final String UPLOADFORM = "uploadform";

    public static final String QUAKE_DOCS = "showdoc";

    private static URL appletURL = null;

    private static URL qURL = null;

    private static URL updateURL = null;

    private static URL uploadForm = null;

    private static URL showdoc = null;

    protected URLUtil(URL appleturl) {

        URLUtil.appletURL = appleturl;

        setURL(QUERY);

        setURL(UPDATE);

        setURL(UPLOADFORM);

        setURL(QUAKE_DOCS);
    }

    public static void init(URL appletURL) {
        if (urlUtil == null) {
            urlUtil = new URLUtil(appletURL);
        }
    }

    public static URL getAppletURL() {
        return appletURL;
    }
    
    /**
     * Gets the url for a server resource.
     * 
     * @param url the server resource identifier
     * @return the corresponding URL
     */
    public static URL getURL(String url) {

        if (url.equals(QUERY)) {
            return qURL;
        }

        else if (url.equals(UPDATE)) {
            return updateURL;
        }

        else if (url.equals(QUAKE_DOCS)) {
            return showdoc;
        }

        else if (url.equals(UPLOADFORM)) {
            return uploadForm;
        }

        try {
            return new URL(url);
        } catch (MalformedURLException ex) {
            return null;
        }

    }

    private static void setURL(String url) {

        try {

            if (url.equals(QUERY)) {
                qURL = new URL(getAppletURL().toString() + QUERY);
            }

            else if (url.equals(UPDATE)) {
                updateURL = new URL(getAppletURL().toString() + UPDATE);
            }

            else if (url.equals(QUAKE_DOCS)) {
                showdoc = new URL(getAppletURL().toString() + QUAKE_DOCS);
            }

            else if (url.equals(UPLOADFORM)) {
                uploadForm = new URL(getAppletURL().toString() + UPLOADFORM);
            }

        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

}
